import { expr2xy } from "../../core/alphabet"
import { isObject, isString } from "../../core/helper"
//表达式方法
export const expressions = {
  SUM(params){
    let echo = 0;
    params.forEach(item=>{
      echo += (parseFloat(item)||0)
    })
    return echo;
  },
  AVERAGE(params){
    let echo = 0;
    params.forEach(item=>{
      echo += (parseFloat(item)||0)
    })
    return (echo/params.length).toFixed(4);
  },
  MAX(params){
    let echo = 0;
    params.forEach(item=>{
      echo += Math.max(parseFloat(item)||0,echo)
    })
    return echo;
  },
  MIN(params){
    let echo = 0;
    params.forEach(item=>{
      echo += Math.min(parseFloat(item)||0,echo)
    })
    return echo;
  },
  IF(condition,ok,error){
    if(condition && condition != 'fasle' && condition != 'null' && condition != '0' && condition != 'undefined'){
      return ok;
    }else{
      return error
    }
  },
  AND(params){
    for(let i = 0; i < params.length; i++){
      let condition = params[i]
      if(condition || condition == 'fasle' || condition == 'null' || condition == '0' || condition == 'undefined'){
        return false;
      }
    }
    return true;
  },
  OR(params){
    for(let i = 0; i < params.length; i++){
      let condition = params[i]
      if(condition && condition != 'fasle' && condition != 'null' && condition != '0' && condition != 'undefined'){
        return true;
      }
    }
    return false;
  },
  CONCAT(params){
    let echo = '';
    params.forEach(item=>{
      echo += item;
    })
    return echo;
  }
}
//条件表达式计算
export function conditionComputed(before,after,op){
  let echo = false;
  let beforeNum = parseFloat(before) || 0,
      afterNum = parseFloat(after) || 0;
  switch(op){
    case '==':
      echo = (beforeNum == afterNum)
      break;
    case '!=':
      echo = (beforeNum != afterNum)
      break;
    case '>':
      echo = (beforeNum > afterNum)
      break;
    case '>=':
      echo = (beforeNum >= afterNum)
      break;
    case '<':
      echo = (beforeNum < afterNum)
      break;
    case '<=':
      echo = (beforeNum <= afterNum)
      break;
    case 'in':
      echo = ((after+'').indexOf(before+'')!=-1)
      break;
    case 'like':
      echo = true;
      break;
  }
  return echo;
}
//是否是表达式
export function isExpression(tableData,cell){
  let {text} = cell;
  let splitArr = (/^=(\w+)\((.+)\)/gi).exec(text) || ['','text','a'];
  let expression = splitArr[1].toLocaleUpperCase(),
      params = splitArr[2].toLocaleUpperCase().split(',');
  if(expressions[expression]){
    let {isBind,cells} = hasBindFiled(tableData,params)
    return {
      isBind,
      relationCells: cells,
      params,
      fun:expressions[expression]
    };
  }
  return false;
}
//过滤数据
export function dataSourceFilter(dataSource,filter=[]){
  if(filter.length == 0)return dataSource;
  let newDataSource = {},dataSourceFilter = {};
  filter.forEach(item=>{
    dataSourceFilter[item.table] = dataSourceFilter[item.table] || [];
    dataSourceFilter[item.table].push(item);
  });
  Object.keys(dataSource).forEach(tableName=>{
    if(tableName in dataSourceFilter){
      newDataSource[tableName] = [];
      dataSource[tableName].forEach(item=>{
        let isOk = true;
        dataSourceFilter[tableName].forEach(filter=>{
          let {code, value, op, join} = filter;
          let result = conditionComputed(item[code]||'',value,op);
          if(isOk){
            switch(join){
              case 'and':
                isOk = isOk && result
                break;
              case 'or':
                isOk = isOk || result
                break;
            }
          }
        })
        if(isOk){
          newDataSource[tableName].push(item)
        }
      })
    }else{
      newDataSource[tableName] = dataSource[tableName];
    }
  })
  return newDataSource;
}
//判断cell中，是否存在bindFiled，是的话return 有bindFiled的cell
export function hasBindFiled (tableData,cells=[]){
  let echo = [],isBind = false;
  cells.forEach(cell=>{
    if(isObject(cell)){
      if(cell.bindFiled){
        isBind = true;
        echo.push(cell);
      }
    }else{
      //普通字符串（表达式中的连接符）
      cell = cell || `"''"`
      if((/^(\"|\')(.*)(\"|\')$/).test(cell)){
        echo.push(cell);
        return
      };
      let itemPos = expr2xy(cell);
      let realCell = tableData.rows[itemPos[1]].cells[itemPos[0]] || {};
      if(realCell.bindFiled){
        isBind = true;
      }
      echo.push(realCell);
    }
  })
  return {isBind,cells: echo};
}
// 获取cells中绑定数据集的最大长度
export function getBindFiledMaxLength(dataSource,cells=[]){
  let echo = 0;
  cells.forEach(cell=>{
    if(cell.bindFiled){
      let bindFiledArr = cell.bindFiled.split('.');
      let dataList = dataSource[bindFiledArr[0]] || [];
      echo = Math.max(echo,dataList.length)
    }
  })
  return echo;
}
//获取对应的tableItem  当前cell对应的第几条{table001:{}}
export const getTableItem = function(datasource,i){
  let echo = {};
  for(let key in datasource){
    echo[key] = datasource[key][i] || {}
  }
  return echo;
}
// 導出excel
export function exportExcel(fileName,tableDom,style=""){
  let totalTableHtml = tableDom.innerHTML;
      totalTableHtml = totalTableHtml.replace(/<tbody>/gi, '');
      totalTableHtml = totalTableHtml.replace(/<\/tbody>/gi, '');
  let newTable = '<table border="1" cellspacing="0" style="border-collapse:collapse;border-color:rgba(0, 0, 0, 0.2);"><tbody>' + totalTableHtml + '</tbody></table>'
  let excelHtml = `<html 
          xmlns:o="urn:schemas-microsoft-com:office:office" 
          xmlns:x="urn:schemas-microsoft-com:office:excel"
          xmlns="http://www.w3.org/TR/REC-html40">
          <head>
            <meta charset=\'utf-8\' />
            <!--[if gte mso 9]>
            <xml>
              <x:ExcelWorkbook>
                <x:ExcelWorksheets>
                  <x:ExcelWorksheet>
                  <x:Name>
                    ${fileName}
                  </x:Name>
                  <x:WorksheetOptions>
                    <x:DisplayGridlines/>
                  </x:WorksheetOptions>
                  </x:ExcelWorksheet>
                </x:ExcelWorksheets>
              </x:ExcelWorkbook>
            </xml>
            <![endif]-->
            <style type="text/css">
              ${style}
            </style> 
          </head>
          <body>
            ${newTable}
          </body>
        </html>`;
  let blob =  new Blob([excelHtml], {type: "application/vnd.ms-excel"});
  let a = document.createElement('a');
  a.href = URL.createObjectURL(blob);
  a.download = `${fileName}.xls`;
  a.click();
}